/*
https://leetcode-cn.com/problems/swap-adjacent-in-lr-string/solution/zai-lrzi-fu-chuan-zhong-jiao-huan-xiang-lin-zi-fu-/
 */
public class Solution777 {
    public boolean canTransform(String start, String end) {
        int state=0,num=0;
        for (int i=0;i<start.length();i++){
            if (start.charAt(i)==end.charAt(i)){
                if (state==1 && start.charAt(i)=='L'){
                    return false;
                }
                if (state==2 && start.charAt(i)=='R'){
                    return false;
                }
                continue;
            }
            if (start.charAt(i)=='R' && end.charAt(i)=='X'){
                if (state==2){
                    return false;
                }
                state=1;
                num++;
            }else if (start.charAt(i)=='X' && end.charAt(i)=='R'){
                if (state!=1){
                    return false;
                }
                num--;
                if (num==0){
                    state=0;
                }
            }else if (start.charAt(i)=='X' && end.charAt(i)=='L'){
                if (state==1){
                    return false;
                }
                state=2;
                num++;
            }else if (start.charAt(i)=='L' && end.charAt(i)=='X'){
                if (state!=2){
                    return false;
                }
                num--;
                if (num==0){
                    state=0;
                }
            }else {
                return false;
            }
        }
        return state==0;
    }

    public static void main(String[] args) {
        System.out.println(new Solution777().canTransform("RXXLRXRXL","XRLXXRRLX"));
    }
}
